import React from 'react';
import { Form, Modal, Input, message, Dropdown, Menu, Popconfirm } from 'antd';
import { connect } from 'umi';
import authHelper from '@/utils/auth/helper';
import { Icon } from '../components';
import { updateDemandOwner, quickAccept } from '../service';
import SelectEmployee from './select/SelectEmployee';

const TITLE_MAP = {
    2: '分配负责人',
    3: '修改负责人'
};

const CONFIRM_MAP = {
    2: '需求已分配',
    3: '负责人变更中'
};

function DemandAssign({ form, user = {}, data = {}, onSuccess = () => {}, onClick = () => {}, ...rest }) {
    const { currentUser = {} } = user;
    const {
        principalEmployeeCode = '',
        principalEmployeeName = '--',
        preparePrincipalEmployeeName = '',
        id,
        recruitStatus
    } = data;
    const [visible, setVisible] = React.useState();
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 5 }
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 }
        }
    };

    const handleUpdate = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const { principalChangeReason, employee = {} } = values;
                setConfirmLoading(true);
                try {
                    const res = await updateDemandOwner({
                        id,
                        principalChangeReason,
                        principalEmployeeCode: employee.value,
                        principalEmployeeName: employee.label
                    });
                    if (res.code === 10000) {
                        message.success('分配成功！');
                        onSuccess();
                    } else {
                        message.error(res?.msg);
                    }
                } catch (error) {
                    console.error(error);
                } finally {
                    setConfirmLoading(false);
                }
                onSuccess();
            }
        });
    };

    const handleQuick = async () => {
        try {
            const res = await quickAccept({
                recruitStatus: 3,
                id,
                principalChangeReason: '',
                principalEmployeeCode: currentUser.employeeCode,
                principalEmployeeName: currentUser.employeeName
            });
            if (res.code === 10000) {
                message.success('认领成功！');
                onSuccess();
            } else {
                message.error(res?.msg);
            }
        } catch (error) {
            console.log(error);
        }
    };

    // 是否为当前招聘负责人
    const isCurrentPrincipal = currentUser.employeeCode === principalEmployeeCode;

    const menu = (
        <Menu>
            <Menu.Item onClick={handleQuick}>分配给我</Menu.Item>
            <Menu.Item
                onClick={() => {
                    setVisible(true);
                }}
            >
                分配给其他人
            </Menu.Item>
        </Menu>
    );

    const [confirm, setConfirm] = React.useState(!preparePrincipalEmployeeName);

    const icon = <Icon title={TITLE_MAP[recruitStatus]} type="zhidingfuzeren" onClick={onClick} {...rest} />;
    // console.log('===============================================>render');

    const renderBtn = () => {
        // 没有待接受且不是当前负责人，则只能分配给其他人
        if (!preparePrincipalEmployeeName && isCurrentPrincipal) {
            return (
                <Icon
                    onClick={() => {
                        onClick();
                        setVisible(true);
                    }}
                    title={TITLE_MAP[recruitStatus]}
                    type="zhidingfuzeren"
                    {...rest}
                />
            );
        }
        // 没有待接受且不是当前负责人，则可以分配给自己
        if (!preparePrincipalEmployeeName && !isCurrentPrincipal) {
            return (
                <Dropdown trigger={['click']} overlay={menu}>
                    {icon}
                </Dropdown>
            );
        }
        return (
            <Popconfirm
                disabled={!preparePrincipalEmployeeName}
                placement="bottomRight"
                title={`${CONFIRM_MAP[recruitStatus]}，待${preparePrincipalEmployeeName}接受，是否继续修改`}
                onConfirm={() => {
                    if (!isCurrentPrincipal) {
                        setConfirm(true);
                        return;
                    }
                    setVisible(true);
                }}
                onCancel={() => {
                    setConfirm(false);
                }}
                okText="是"
                cancelText="否"
            >
                {confirm ? (
                    <Dropdown
                        visible={confirm && !isCurrentPrincipal}
                        overlay={menu}
                        onVisibleChange={value => {
                            setConfirm(value);
                        }}
                    >
                        {icon}
                    </Dropdown>
                ) : (
                    icon
                )}
            </Popconfirm>
        );
    };

    // 非招聘负责人且未授权修改招聘负责人权限，则返回 null
    if (!isCurrentPrincipal && !authHelper.checkCode('office:recruitment:course:requirement:principal:edit')) {
        return null;
    }

    return (
        <>
            {renderBtn()}
            <Modal
                width={600}
                title={TITLE_MAP[recruitStatus]}
                visible={visible}
                confirmLoading={confirmLoading}
                onOk={handleUpdate}
                onCancel={() => {
                    setVisible(false);
                }}
                afterClose={() => {
                    form.setFieldsValue({
                        employee: '',
                        principalChangeReason: ''
                    });
                }}
            >
                <Form {...formItemLayout}>
                    {principalEmployeeName && <Form.Item label="现有负责人">{principalEmployeeName}</Form.Item>}
                    <Form.Item label="招聘负责人">
                        {form.getFieldDecorator('employee', {
                            rules: [{ required: true, message: '招聘负责人不能为空' }]
                        })(<SelectEmployee params={{ id }} />)}
                    </Form.Item>
                    <Form.Item label="变更原因">
                        {form.getFieldDecorator('principalChangeReason', {
                            rules: [{ required: true, message: '变更原因不能为空' }]
                        })(<Input.TextArea rows={5} placeholder="请输入" maxLength={100} />)}
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
}

export default connect(({ user }) => ({ user }))(Form.create()(DemandAssign));
